﻿using Quartz;
using SX.Core;
using SX.Data;
using SX.Utils;
using SX.Utils.Log.log4net;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Ly.Scheduler.Common
{
    /// <summary>
    /// 同步电池信息
    /// </summary>
    [DisallowConcurrentExecution]
    public class SyncBatteryJob : IJob
    {
        private readonly ILog logger = LogManager.GetLogger(typeof(SyncBatteryJob));
        public void Execute(IJobExecutionContext context)
        {
            logger.Info("开始同步电池信息");
            var lydb = Db.Context("LYDB");
            var lyNewdb = Db.Context("LYNew");
            List<dynamic>  dataList = lydb.Sql("SELECT DISTINCT b.BatteryCode , b.BatteryName ,  b.BatteryQty , b.BatterySpec    FROM ProductBattery(NOLOCK) b").QueryMany<dynamic>();
            foreach (dynamic data in dataList)
            {
                string BatteryCode = CommonHelper.ToString(data.BatteryCode);
                string BatteryName = CommonHelper.ToString(data.BatteryName);
                string BatterySpec = CommonHelper.ToString(data.BatterySpec);
                int BatteryQty = CommonHelper.ToInt(data.BatteryQty);
                lyNewdb.Sql(@"insert into wh_battery_info(battery_code,battery_name,battery_spec,whpi_status,battery_amount,create_id,update_id)
                    values(@battery_code,@battery_name,@battery_spec,@whpi_status,@battery_amount,1,1) ON CONFLICT(battery_code) 
                    do update 
                    set battery_code=EXCLUDED.battery_code,
                    battery_name=EXCLUDED.battery_name,
                    battery_spec=EXCLUDED.battery_spec ,
                    whpi_status=EXCLUDED.whpi_status,
                    battery_amount=EXCLUDED.battery_amount,
                    update_time=now();  ")
                .Parameter("battery_code", BatteryCode, DataTypes.String) 
                .Parameter("battery_name", BatteryName, DataTypes.String)
                .Parameter("battery_spec", BatterySpec, DataTypes.String)
                .Parameter("whpi_status", 0, DataTypes.Int32)
                .Parameter("battery_amount", BatteryQty, DataTypes.Int32) 
                .Execute();
            } 
            logger.Info("同步电池信息完成");
        } 
    }
}
